package com.cskaoyan.service;

import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.wx.cart.bo.*;
import com.cskaoyan.bean.wx.cart.vo.CartCheckoutCheckedAddressVo;
import com.cskaoyan.bean.wx.cart.vo.CartCheckoutVo;
import com.cskaoyan.bean.wx.cart.vo.CartIndexCartTotalVo;
import com.cskaoyan.bean.wx.cart.vo.CartIndexVo;
import com.cskaoyan.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lwq
 * @since 2022/11/22 15:59
 */
@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;

    /**
     * 统计购物车所有商品数量
     *
     * @param userId
     * @return int
     * @author lwq
     * @since 2022/11/22 17:04
     */
    @Override
    public int goodsCount(int userId) {
        Integer goodsCount = marketCartMapper.selectGoodsCount(userId);
        if (goodsCount == null) {
            return 0;
        }
        return goodsCount;
    }

    /**
     * 购物车页面
     *
     * @return com.cskaoyan.bean.wx.cart.vo.CartIndexVo
     * @author lwq
     * @since 2022/11/22 16:02
     */
    @Override
    public CartIndexVo index(int userId) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        // 查询该用户购物车中所有商品
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        if (marketCarts != null) {
            CartIndexVo cartIndexVo = new CartIndexVo();
            cartIndexVo.setCartList(marketCarts);
            Integer goodsCount = goodsCount(userId);
            if (goodsCount == null) {
                goodsCount = 0;
            }
            Double goodsAmount = marketCartMapper.selectGoodsAmount(userId);
            if (goodsAmount == null) {
                goodsAmount = 0.0;
            }
            Integer checkedGoodsCount = marketCartMapper.selectCheckedGoodsCount(userId);
            if (checkedGoodsCount == null) {
                checkedGoodsCount = 0;
            }
            Double checkedGoodsAmount = marketCartMapper.selectCheckedGoodsAmount(userId);
            if (checkedGoodsAmount == null) {
                checkedGoodsAmount = 0.0;
            }
            CartIndexCartTotalVo cartIndexCartTotalVo = new CartIndexCartTotalVo(goodsCount, checkedGoodsCount, goodsAmount, checkedGoodsAmount);
            cartIndexVo.setCartTotal(cartIndexCartTotalVo);
            return cartIndexVo;
        }
        return null;
    }

    /**
     * 添加商品至购物车
     *
     * @param cartAddBo
     * @param userId
     * @return int
     * @author lwq
     * @since 2022/11/22 17:28
     */
    @Override
    public int add(CartAddBo cartAddBo, int userId) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andProductIdEqualTo(cartAddBo.getProductId());
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        if (marketCarts.size() != 0) {
            // 购物车中存在该商品 增加数量
            for (MarketCart marketCart : marketCarts) {
                marketCart.setNumber((short) (marketCart.getNumber() + cartAddBo.getNumber()));
                marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
                return goodsCount(userId);
            }
        }
        MarketCart marketCart = createMarketCart(cartAddBo, userId);
        marketCartMapper.insertSelective(marketCart);
        return goodsCount(userId);
    }

    private MarketCart createMarketCart(CartAddBo cartAddBo, int userId) {
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(cartAddBo.getGoodsId());
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(cartAddBo.getProductId());
        MarketCart marketCart = new MarketCart(null, userId, cartAddBo.getGoodsId(), marketGoods.getGoodsSn(), marketGoods.getName(), cartAddBo.getProductId(), marketGoodsProduct.getPrice(), cartAddBo.getNumber().shortValue(), marketGoodsProduct.getSpecifications(), true, marketGoodsProduct.getUrl(), new Date(), new Date(), false);
        return marketCart;
    }

    /**
     * 修改购物车
     *
     * @param cartUpdateBo
     * @param userId
     * @return int
     * @author lwq
     * @since 2022/11/22 19:34
     */
    @Override
    public int update(CartUpdateBo cartUpdateBo, int userId) {
        MarketCart marketCart = new MarketCart();
        marketCart.setNumber(cartUpdateBo.getNumber().shortValue());
        marketCart.setUpdateTime(new Date());
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        criteria.andIdEqualTo(cartUpdateBo.getId());
        int affectedRows = marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        return affectedRows;
    }

    /**
     * 选择商品
     *
     * @param cartCheckedBo
     * @param userId
     * @return com.cskaoyan.bean.wx.cart.vo.CartIndexVo
     * @author lwq
     * @since 2022/11/22 19:49
     */
    @Override
    public CartIndexVo checked(CartCheckedBo cartCheckedBo, int userId) {
        MarketCart marketCart = new MarketCart();
        marketCart.setChecked(cartCheckedBo.getIsChecked().equals(1));
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        criteria.andProductIdIn(cartCheckedBo.getProductIds());
        marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        return index(userId);
    }

    /**
     * 添加购物车并付款
     *
     * @param cartAddBo
     * @param userId
     * @return int
     * @author lwq
     * @since 2022/11/22 20:10
     */
    @Override
    public int fastAdd(CartAddBo cartAddBo, int userId) {
        MarketCart marketCart = createMarketCart(cartAddBo, userId);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("fastAdd", marketCart);
        // 代表不插入数据库
        return -1;
    }

    /**
     * 下单
     *
     * @param cartCheckoutBo
     * @param userId
     * @return com.cskaoyan.bean.wx.cart.vo.CartCheckoutVo
     * @author lwq
     * @since 2022/11/23 10:08
     */
    @Override
    public CartCheckoutVo checkout(CartCheckoutBo cartCheckoutBo, int userId) {
        CartCheckoutVo cartCheckoutVo = new CartCheckoutVo();
        // 地址信息
        if (cartCheckoutBo.getAddressId() != 0) {
            MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(cartCheckoutBo.getAddressId());
            CartCheckoutCheckedAddressVo cartCheckoutCheckedAddressVo = new CartCheckoutCheckedAddressVo(marketAddress.getId(), marketAddress.getName(), marketAddress.getUserId(), marketAddress.getProvince(), marketAddress.getCity(), marketAddress.getCounty(), marketAddress.getAddressDetail(), marketAddress.getAreaCode(), marketAddress.getTel(), marketAddress.getIsDefault(), marketAddress.getAddTime(), marketAddress.getUpdateTime(), marketAddress.getDeleted());
            cartCheckoutVo.setCheckedAddress(cartCheckoutCheckedAddressVo);
            cartCheckoutVo.setAddressId(cartCheckoutBo.getAddressId());
        }
        // 团购信息 暂不实现
        cartCheckoutVo.setGrouponPrice(0.0);
        cartCheckoutVo.setGrouponRulesId(0);
        // 运费信息 运费8元，满88元免运费
        MarketSystemExample marketSystemExample = new MarketSystemExample();
        MarketSystemExample.Criteria marketSystemExampleCriteria = marketSystemExample.createCriteria();
        double freightMin = 0;
        double freightValue = 0;
        marketSystemExampleCriteria.andKeyNameLike("market_express_freight_%");
        List<MarketSystem> marketSystems = marketSystemMapper.selectByExample(marketSystemExample);
        for (MarketSystem marketSystem : marketSystems) {
            if ("market_express_freight_min".equals(marketSystem.getKeyName())) {
                freightMin = Double.parseDouble(marketSystem.getKeyValue());
            }
            if ("market_express_freight_value".equals(marketSystem.getKeyName())) {
                freightValue = Double.parseDouble(marketSystem.getKeyValue());
            }
        }
        // 商品信息
        cartCheckoutVo.setCartId(cartCheckoutBo.getCartId());
        if (cartCheckoutBo.getCartId() == 0) {
            // 购物车页面中下单，查询选中商品
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andUserIdEqualTo(userId);
            criteria.andCheckedEqualTo(true);
            List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
            cartCheckoutVo.setCheckedGoodsList(marketCarts);
            Double checkedGoodsAmount = marketCartMapper.selectCheckedGoodsAmount(userId);
            cartCheckoutVo.setGoodsTotalPrice(checkedGoodsAmount);
            if (checkedGoodsAmount >= freightMin) {
                cartCheckoutVo.setFreightPrice(0.0);
            } else {
                cartCheckoutVo.setFreightPrice(freightValue);
            }
        } else {
            // 商品页面下单，只算该商品
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            MarketCart marketCart = (MarketCart) session.getAttribute("fastAdd");
            // MarketCart marketCart = marketCartMapper.selectByPrimaryKey(cartCheckoutBo.getCartId());
            List<MarketCart> marketCarts = new ArrayList<>();
            marketCarts.add(marketCart);
            cartCheckoutVo.setCheckedGoodsList(marketCarts);
            double checkedGoodsAmount = marketCart.getNumber() * marketCart.getPrice().doubleValue();
            cartCheckoutVo.setGoodsTotalPrice(checkedGoodsAmount);
            if (checkedGoodsAmount >= freightMin) {
                cartCheckoutVo.setFreightPrice(0.0);
            } else {
                cartCheckoutVo.setFreightPrice(freightValue);
            }
        }
        // 优惠信息
        if (cartCheckoutBo.getCouponId() == 0) {
            cartCheckoutVo.setCouponId(-1);
        } else {
            cartCheckoutVo.setCouponId(cartCheckoutBo.getCouponId());
        }
        cartCheckoutVo.setUserCouponId(cartCheckoutBo.getUserCouponId());
        // 查询用户可用优惠券数量
        int availableCouponLength = marketCouponUserMapper.selectAvailableCouponLength(userId, cartCheckoutVo.getGoodsTotalPrice());
        cartCheckoutVo.setAvailableCouponLength(availableCouponLength);
        if (cartCheckoutBo.getCouponId() != -1 && cartCheckoutBo.getCouponId() != 0) {
            // 查询优惠券
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(cartCheckoutBo.getCouponId());
            cartCheckoutVo.setCouponPrice(marketCoupon.getDiscount().doubleValue());
        } else {
            // 不使用优惠券
            cartCheckoutVo.setCouponPrice(0.0);
        }
        cartCheckoutVo.setActualPrice(cartCheckoutVo.getGoodsTotalPrice() - cartCheckoutVo.getCouponPrice());
        cartCheckoutVo.setOrderTotalPrice(cartCheckoutVo.getActualPrice());
        return cartCheckoutVo;
    }

    /**
     * 删除购物车中的商品
     *
     * @param cartDeleteBo
     * @param userId
     * @return com.cskaoyan.bean.wx.cart.vo.CartIndexVo
     * @author lwq
     * @since 2022/11/23 15:23
     */
    @Override
    public CartIndexVo delete(CartDeleteBo cartDeleteBo, int userId) {
        MarketCart marketCart = new MarketCart();
        marketCart.setDeleted(true);
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andProductIdIn(cartDeleteBo.getProductIds());
        int affectedRows = marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        if (affectedRows == cartDeleteBo.getProductIds().size()) {
            CartIndexVo cartIndexVo = index(userId);
            cartIndexVo.getCartTotal().setCheckedGoodsAmount(0.0);
            cartIndexVo.getCartTotal().setCheckedGoodsCount(0);
            return cartIndexVo;
        }
        return null;
    }

}
